from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend
from django.db import transaction
from .models import Equipment
from .serializers import EquipmentSerializer


class EquipmentViewSet(viewsets.ModelViewSet):
    """
    设备资源视图集
    提供设备资源的增删改查功能
    """
    queryset = Equipment.objects.all().order_by('id')
    serializer_class = EquipmentSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['organization', 'device_name']

    def create(self, request, *args, **kwargs):
        """
        创建设备资源
        """
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '设备资源创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)
        return Response({
            'success': False,
            'message': '数据验证失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, *args, **kwargs):
        """
        更新设备资源
        """
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '设备资源更新成功',
                'data': serializer.data
            })
        return Response({
            'success': False,
            'message': '数据验证失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

    def destroy(self, request, *args, **kwargs):
        """
        删除设备资源
        """
        instance = self.get_object()
        instance.delete()
        return Response({
            'success': True,
            'message': '设备资源删除成功'
        }, status=status.HTTP_204_NO_CONTENT)

    def list(self, request, *args, **kwargs):
        """
        获取设备资源列表（不分页）
        """
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'success': True,
            'data': serializer.data
        })

    @action(detail=False, methods=['post'])
    def batch_create(self, request):
        """
        批量创建设备资源
        """
        data_list = request.data.get('equipment_list', [])
        if not data_list:
            return Response({
                'success': False,
                'message': '请提供设备资源数据'
            }, status=status.HTTP_400_BAD_REQUEST)

        created_equipment = []
        errors = []
        
        with transaction.atomic():
            for i, data in enumerate(data_list):
                serializer = self.get_serializer(data=data)
                if serializer.is_valid():
                    equipment = serializer.save()
                    created_equipment.append(serializer.data)
                else:
                    errors.append({
                        'index': i,
                        'errors': serializer.errors
                    })
        
        if errors:
            return Response({
                'success': False,
                'message': '部分数据验证失败',
                'errors': errors,
                'created': created_equipment
            }, status=status.HTTP_400_BAD_REQUEST)
        
        return Response({
            'success': True,
            'message': f'成功创建{len(created_equipment)}条设备资源',
            'data': created_equipment
        }, status=status.HTTP_201_CREATED)

    @action(detail=False, methods=['delete'])
    def batch_delete(self, request):
        """
        批量删除设备资源
        """
        ids = request.data.get('ids', [])
        if not ids:
            return Response({
                'success': False,
                'message': '请提供要删除的设备资源ID'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        deleted_count = Equipment.objects.filter(id__in=ids).delete()[0]
        return Response({
            'success': True,
            'message': f'成功删除{deleted_count}条设备资源'
        })
